import json
from urllib.parse import urlencode, parse_qs

import requests
from django.conf import settings


class OAuthQQ(object):
    """ QQ认证辅助工具类 """
    def __init__(self, client_id = None, client_secret = None, redirect_uri = None, state = None):
        """
        初始化QQ登录对象
        :param client_id:
        :param client_secret:
        :param redirect_uri:
        :param state:
        """
        self.client_id = client_id or settings.QQ_CLIENT_ID
        self.client_secret = client_secret or settings.QQ_CLIENT_SECRET
        self.redirect_uri = redirect_uri or settings.QQ_REDIRECT_URI
        self.state = state or settings.QQ_STATE  # 用于保存登录成功后的跳转页面路径


    def get_qq_url(self):
        """
        获取QQ登录链接
        :return:
        """
        data_dict = {
            'response_type': 'code',
            'client_id': self.client_id,
            'redirect_uri': self.redirect_uri,
            'state': self.state
        }
        # 构造QQ登录链接==>查询字符串
        qq_url = 'https://graph.qq.com/oauth2.0/authorize?'+ urlencode(data_dict)
        return qq_url

    def get_access_token(self, code):
        """
        获取access_token值
        :param code:
        :return:
        """
        # 构建参数数据
        data_dict = {
            'grant_type': 'authorization_code',
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'redirect_uri': self.redirect_uri,
            'code': code
        }

        # 构建url
        access_url = 'https://graph.qq.com/oauth2.0/token?' + urlencode(data_dict)

        # 发送请求
        try:
            response = requests.get(access_url)

            # 提取数据
            # access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14
            data = response.text

            # 转化为字典
            data = parse_qs(data)
        except:
            raise Exception('qq请求失败')

        # 提取access_token
        access_token = data.get('access_token', None)

        if not access_token:
            raise Exception('access_token获取失败')

        return access_token[0]

    def get_open_id(self, access_token):
        """
        获取openid
        :param access_token:
        :return:
        """
        # 构建请求url
        url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token

        # 发送请求
        try:
            response = requests.get(url)

            # 提取数据
            # callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
            # code=asdasd&msg=asjdhui  错误的时候返回的结果
            data = response.text
            data = data[10:-3]
        except:
            raise Exception('qq请求失败')
            # 转化为字典
        try:
            data_dict = json.loads(data)
            # 获取openid
            print("data:%s" % data_dict)
            openid = data_dict.get('openid')
        except:
            raise Exception('openid获取失败')

        return openid



class OAuthWeibo(object):
    """ 微博认证辅助工具类 """
    def __init__(self,client_id = None, client_secret = None, redirect_uri = None, state=None):
        self.client_id = client_id or settings.WEIBO_CLIENT_ID
        self.redirect_uri = redirect_uri or settings.WEIBO_REDIRECT_URI
        self.client_secret=client_secret or settings.WEIBO_CLIENT_SECRET
        self.state = state or settings.WEIBO_STATE

    def get_weibo_url(self):
        """
        获取微博的验证页面链接
        :return:
        """
        data_dict = {
            'client_id': self.client_id,
            'redirect_uri': self.redirect_uri,
            'state':self.state
        }
        # print(data_dict)
        # 构造微博登录链接
        weibo_url = 'https://api.weibo.com/oauth2/authorize?' + urlencode(data_dict)
        return weibo_url

    def get_access_token(self, code):
        """
        获取微博的accesstoken值
        https://api.weibo.com/oauth2/access_token
        ?client_id=YOUR_CLIENT_ID
        &client_secret=YOUR_CLIENT_SECRET
        &grant_type=authorization_code
        &redirect_uri=YOUR_REGISTERED_REDIRECT_URI
        &code=CODE

        :param code:
        :return:
        """
        # 构造参数
        data_dict = {
            "client_id":self.client_id,
            "client_secret":self.client_secret,
            "grant_type":"authorization_code",
            "redirect_uri":self.redirect_uri,
            "code":code
        }

        # 发送请求
        url = "https://api.weibo.com/oauth2/access_token"
        try:
            response = requests.post(url=url,data=data_dict)

            # 提取数据
            # {
            #     "access_token": "SlAV32hkKG",
            #     "remind_in": 3600,
            #     "expires_in": 3600
            # }
            data = response.text
            data_dict = json.loads(data)
            access_token = data_dict["access_token"]
            print(data_dict)
        except:
            raise Exception('微博请求失败')
        return access_token

